# coding=utf-8
"""
Created on 2018年09月07日
"""
import weakref
from service_base.article_service import ArticleService
from util_base.ufo_decorators import processor
from common_base.cmd import CMD
from processor_base.base_processor import BaseProcessor
from util_base.exception import ParamException, UFOException as E
from common_base.errors import AliveError
from common_base.constants import UFOConstant


@processor(CMD.CMD_UGC_GET_WEEKLY_HOT_ARTICLE_LIST, internal_access=True)
class GetWeeklyHotArticleList(BaseProcessor):
    """
    GetWeeklyHotArticleList
    """
    
    TAG = 'GetWeeklyHotArticleList'
    
    def __init__(self, handler):
        """
        Constructor
        """
        BaseProcessor.__init__(self, handler)
        self._article_service = ArticleService(weakref.proxy(self))

    def process(self):
        """
        process protocol
        """
        userid = self.alive_cmsdb.get_userid_by_userkey(self.user_key)
        if not userid:
            raise E(AliveError.ERROR_USER_DOES_NOT_EXIST)

        # 分页参数
        page_size = UFOConstant.PAGE_SIZE_WEEKLY_HOT_ARTICLE_LIST

        if self.p_article_id_list:
            # 首次带帖子进入hot列表
            if not self.last_article_order_id:
                # 查询带入的帖子
                db_self_articles = self.alive_cmsdb.get_articles_by_article_id_list(list(set(self.p_article_id_list)))
                self_articles_dict_data = {e['articleId']: e for e in db_self_articles}
                # 查询周最热帖子
                db_weekly_hot_articles = self.alive_cmsdb.get_weekly_hot_articles(userid, page_size)
                # 去重
                rd_weekly_hot_articles = self.remove_duplicate_articles(self.p_article_id_list, db_weekly_hot_articles)
                # 带入的帖子 + hot帖子
                target_weekly_hot_articles = [self_articles_dict_data[each_article_id] for each_article_id in self.p_article_id_list]
                target_weekly_hot_articles.extend(rd_weekly_hot_articles)

            else:
                # # 查询周最热帖子
                db_weekly_hot_articles = self.alive_cmsdb.get_weekly_hot_articles(userid, page_size, order_id=self.last_article_order_id)
                # 去重
                target_weekly_hot_articles = self.remove_duplicate_articles(self.p_article_id_list, db_weekly_hot_articles)

        else:
            # 获取周最热帖子的排序id
            order_id = self.last_article_order_id if self.last_article_order_id else None
            target_weekly_hot_articles = self.alive_cmsdb.get_weekly_hot_articles(userid, page_size, order_id=order_id)

        # # 确定最后一个帖子的排序id
        # return_last_article_order_id = ''
        # desc_articles = target_weekly_hot_articles[::-1]
        # for each_article in desc_articles:
        #     this_article_id = each_article['articleId']
        #     return_last_article_order_id = self.alive_cmsdb.get_weekly_hot_article_order_id_by_article_id(this_article_id)
        #     if return_last_article_order_id:
        #         break
        return_last_article_order_id = '0000000000700000000000000000001'  # 最小的排序id,为防止数据库查询崩溃
        if target_weekly_hot_articles:
            last_article = target_weekly_hot_articles[-1]
            if last_article:
                last_article_order_id = last_article.get('orderId')
                if last_article_order_id:
                    return_last_article_order_id = last_article_order_id

        # 组装帖子返回数据
        return_artiles = self._article_service.batch_deal_articles_return_data(
            userid, target_weekly_hot_articles, comments_page_size=UFOConstant.PAGE_SIZE_FOR_YOU_EACH_ARTICLE_COMMENTS
        )

        return dict(
            articleList=return_artiles,
            lastArticleOrderId=return_last_article_order_id
        )

    def remove_duplicate_articles(self, self_article_ids, p_articles):
        """
        将用户带入的帖子从数据库中查出的帖子列表中过滤掉
        """
        return [e for e in p_articles if e['articleId'] not in self_article_ids]

    def _verify_params(self):
        """
        重写父类方法, 作参数校验
        """
        self.p_article_id_list = self.params.get('articleIds', list())  # 从发现页带入的帖子
        self.last_article_order_id = self.params.get('lastArticleOrderId', '')
